interface IPlace {
  street_number: string | null;
  route: string | null;
  city: string | null;
  state: string | null;
  country: string | null;
  postal_code: string | null;
}

function useAutocompleteService(
  input: HTMLInputElement,
  listener: {
    change: (place: IPlace) => void;
  }
) {
  const { change } = listener;
  const component_form = {
    street_number: 'short_name',
    route: 'short_name',
    locality: 'short_name',
    administrative_area_level_1: 'short_name',
    country: 'short_name',
    postal_code: 'short_name',
  };
  const options = {
    types: ['(regions)'],
    componentRestrictions: { country: ['us'] },
  };
  const autoComplete = new google.maps.places.Autocomplete(input, options);
  autoComplete.addListener('place_changed', () => {
    const place = autoComplete.getPlace();
    const result = {
      street_number: null,
      route: null,
      locality: null, // city
      administrative_area_level_1: null, // state
      country: null,
      postal_code: null,
    };

    const address_components = place.address_components || [];
    address_components.forEach((component) => {
      const address_type = component.types[0];
      // @ts-ignore
      if (component_form[address_type]) {
        // @ts-ignore
        result[address_type] = component[component_form[address_type]];
      }
    });

    console.log('google.maps.places.Autocomplete address components', address_components);

    const location = {
      street_number: result.street_number,
      route: result.route,
      city: result.locality,
      state: result.administrative_area_level_1,
      country: result.country,
      postal_code: result.postal_code,
    };
    change(location);
  });
}

export { useAutocompleteService };
